package co.fitstart.mobile.web.controller.moyu;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import com.demo2do.core.BusinessException;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.wechat.pay.TradeType;
import com.demo2do.core.wechat.pay.WechatWebPayConfig;
import com.demo2do.core.wechat.support.AppType;
import com.demo2do.core.wechat.web.handler.JsApiHandler;

import co.fitstart.entity.order.MoyuAddress;
import co.fitstart.entity.order.MoyuOrder;
import co.fitstart.entity.order.MoyuProduct;
import co.fitstart.mobile.Constant;
import co.fitstart.mobile.KdniaoUtils;
import co.fitstart.mobile.entity.trading.MoyuShopping;
import co.fitstart.mobile.handler.PaymentHandler;
import co.fitstart.mobile.service.MoyuAddressService;
import co.fitstart.mobile.service.MoyuProductService;
import co.fitstart.mobile.service.MoyuService;

@Controller
//@RequestMapping("/moyu")
public class MoyuController {

    private static final Logger logger = LoggerFactory.getLogger(MoyuController.class);

    @Autowired
    private MoyuService moyuService;

    @Autowired
    private MoyuAddressService moyuAddressService;

    @Autowired
    private MoyuProductService moyuProductService;

    private String openidKey = Constant.OPENID_KEY;

    @Autowired
    private PaymentHandler paymentHandler;

    @Autowired
    private JsApiHandler jsApiHandler;

    /**
     * list product by type
     * 
     * @param type
     * @param distributorId
     * @return
     */
//    @RequestMapping(value = "", method = RequestMethod.GET)
//    @Router(targetUrl = "/required-wechat")
//    @WechatAuthority
//    @MobileDetect(autoLogin = false)
//    @WechatJsConfig
    public ModelAndView view() {
        ModelAndView modelAndView = new ModelAndView("product/moyu-detail");

        MoyuProduct product = moyuProductService.load(MoyuProduct.class, new Long(1));
        modelAndView.addObject("product", product);

        return modelAndView;
    }

    /**
     * 
     * @param ammount
     * @param type
     * @return
     */
//    @RequestMapping(value = "/shop", method = RequestMethod.GET)
//    @Router(targetUrl = "/required-wechat")
//    @WechatAuthority
//    @MobileDetect(autoLogin = false)
//    @WechatJsConfig
    public ModelAndView shop(@RequestParam("amount") Integer ammount, @RequestParam("type") String type, HttpServletRequest request) {

        ModelAndView modelAndView = new ModelAndView("product/moyu-shop");

        BigDecimal singlePrice = new BigDecimal("118");
        BigDecimal totalPrice = singlePrice.multiply(new BigDecimal(ammount));
        modelAndView.addObject("totalPrice", totalPrice);

        // Get user's openid
        Cookie cookie = WebUtils.getCookie(request, openidKey);
        String openid = cookie != null ? cookie.getValue() : null;
        logger.trace("PaymentController#wechatpayPrepare() - Get openid [{}] from cookie.", openid);

        List<MoyuAddress> moyuAddresses = moyuAddressService.list(openid);
        modelAndView.addObject("moyuAddresses", moyuAddresses);

        for (MoyuAddress moyuAddress : moyuAddresses) {
            if (moyuAddress.isRemarked()) {
                modelAndView.addObject("defaultAddress", moyuAddress);
                break;
            }
        }

        return modelAndView;
    }


//    @RequestMapping(value = "/orders", method = RequestMethod.POST)
    public @ResponseBody String onSumitOrder(MoyuShopping moyuShopping, HttpServletRequest request) {
        Result result = new Result();

        try {

            // Get user's openid
            Cookie cookie = WebUtils.getCookie(request, openidKey);
            String openid = cookie != null ? cookie.getValue() : null;
            logger.trace("PaymentController#wechatpayPrepare() - Get openid [{}] from cookie.", openid);

            MoyuOrder moyuOrder = new MoyuOrder(moyuShopping.getAmount(), moyuShopping.getType(), moyuShopping.getName(), moyuShopping.getMobile(), moyuShopping.getPcd(), moyuShopping.getAddress(), Integer.valueOf("11800"), openid);

            moyuService.saveOrder(moyuOrder);

            result.success().data("orderId", moyuOrder.getId()).message("创建订单成功");

        } catch (BusinessException e) {

            result.fail().message(e.getMessage());

        } catch (Exception e) {

            logger.error("#onSumitOrder() error ", e);

            result.fail().message("创建订单失败");

        }

        return JsonUtils.toJsonString(result);
    }


    /**
     * 
     * @param userContext
     * @param user
     * @param orderId
     * @param currentUrl
     * @param request
     * @return
     */
    //@RequestMapping(value = "/wxpay/prepare", method = RequestMethod.POST)
    public @ResponseBody String wechatpayPrepare(@RequestParam("orderId") Long orderId, @RequestParam("currentUrl") String currentUrl, HttpServletRequest request) {

        Result result = new Result();

        MoyuOrder order = moyuService.load(MoyuOrder.class, orderId);

        // Get user's openid
        Cookie cookie = WebUtils.getCookie(request, openidKey);
        String openid = cookie != null ? cookie.getValue() : null;
        logger.trace("PaymentController#wechatpayPrepare() - Get openid [{}] from cookie.", openid);

        // Get remote IP address, check NGINX real IP header first
        String xRealIpHeader = request.getHeader("X-Real-IP"); // Only available after NGINX
                                                               // redirect
        String remoteIp = StringUtils.isBlank(xRealIpHeader) ? request.getRemoteAddr() : xRealIpHeader;
        logger.trace("PaymentController#wechatpayPrepare() - Get remote IP address [{}].", remoteIp);

        // Construct necessary request data
        Map<String, String> parameters = new HashMap<String, String>();
        parameters.put("total_fee", String.valueOf(order.getPayingPrice()));
        parameters.put("body", "人马君魔芋面购买");
        parameters.put("spbill_create_ip", remoteIp);
        parameters.put("trade_type", TradeType.JSAPI.toString().toUpperCase());
        parameters.put("openid", openid);

        // Request cashier for WeChat prepay id
        Result prepayResult = paymentHandler.preparePay(order.getCode(), String.valueOf(order.getId()), "WECHAT_WEB", parameters);

        if (prepayResult.isValid()) {

            // Get prepay id and generate JS and pay configuration
            String prepayId = (String) prepayResult.get("prepayId");
            com.demo2do.core.wechat.support.WechatJsConfig jsConfig = jsApiHandler.generateJsConfig(AppType.OFFICIAL, currentUrl);
            WechatWebPayConfig payConfig = jsApiHandler.generateWechatWebPayConfig(AppType.OFFICIAL, prepayId);

            if (jsConfig != null && payConfig != null) {
                result.success().data("payConfig", payConfig).data("jsConfig", jsConfig);
            } else {
                result.fail().message("支付数据生成失败");
            }
        } else {
            result.fail().message(prepayResult.getMessage());
        }

        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param orderId
     * @param request
     * @return
     */
//    @RequestMapping(value = "/success", method = RequestMethod.GET)
//    @Router(targetUrl = "/required-wechat")
//    @WechatAuthority
//    @MobileDetect(autoLogin = false)
//    @WechatJsConfig
    public ModelAndView success(@RequestParam("orderId") Long orderId, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("product/moyu-success");
        
        Cookie cookie = WebUtils.getCookie(request, openidKey);
        String openid = cookie != null ? cookie.getValue() : null;
        logger.trace("PaymentController#wechatpayPrepare() - Get openid [{}] from cookie.", openid);
        
        MoyuOrder order = moyuService.load(MoyuOrder.class, orderId);
        if(order == null) {
            modelAndView.setViewName("product/moyu-error");
            return modelAndView;
        }
        
        if(!StringUtils.equalsIgnoreCase(openid, order.getOpenid())) {
            modelAndView.setViewName("product/moyu-error");
            return modelAndView;
        }
        
        modelAndView.addObject("order", order);
        return modelAndView;
    }
    
    /**
     * 
     * @param request
     * @return
     */
//    @RequestMapping(value = "/orders", method = RequestMethod.GET)
//    @Router(targetUrl = "/required-wechat")
//    @WechatAuthority
//    @MobileDetect(autoLogin = false)
//    @WechatJsConfig
    public ModelAndView orders(HttpServletRequest request) {
        
        ModelAndView modelAndView = new ModelAndView("product/moyu-order-list");
        
        // Get user's openid
        Cookie cookie = WebUtils.getCookie(request, openidKey);
        String openid = cookie != null ? cookie.getValue() : null;
        logger.trace("PaymentController#wechatpayPrepare() - Get openid [{}] from cookie.", openid);
        
        List<MoyuOrder> orders = moyuService.list(openid);
        modelAndView.addObject("orders", orders);
        
        return modelAndView;
        
    }
    
    /**
     * 
     * @param id
     * @param request
     * @return
     */
//    @RequestMapping(value = "/orders/{id}", method = RequestMethod.GET)
//    @Router(targetUrl = "/required-wechat")
//    @WechatAuthority
//    @MobileDetect(autoLogin = false)
//    @WechatJsConfig
    public ModelAndView ordersDetail(@PathVariable("id") Long id, HttpServletRequest request) {
        
        ModelAndView modelAndView = new ModelAndView("product/moyu-order-detail");
        
        // Get user's openid
        Cookie cookie = WebUtils.getCookie(request, openidKey);
        String openid = cookie != null ? cookie.getValue() : null;
        logger.trace("PaymentController#wechatpayPrepare() - Get openid [{}] from cookie.", openid);
        
        MoyuOrder order = moyuService.load(MoyuOrder.class, id);
        if(order == null) {
            modelAndView.setViewName("product/moyu-error");
            return modelAndView;
        }
        
        if(!StringUtils.equalsIgnoreCase(openid, order.getOpenid())) {
            modelAndView.setViewName("product/moyu-error");
            return modelAndView;
        }
        
        modelAndView.addObject("order", order);
        
        return modelAndView;
    }
    
//    @RequestMapping(value = "/orders/{id}/wuliu", method = RequestMethod.GET)
//    @Router(targetUrl = "/required-wechat")
//    @WechatAuthority
//    @MobileDetect(autoLogin = false)
//    @WechatJsConfig
public ModelAndView orderWuliu(@PathVariable("id") Long id, HttpServletRequest request) {
        
        ModelAndView modelAndView = new ModelAndView("product/moyu-order-wuliu");
        
        // Get user's openid
        Cookie cookie = WebUtils.getCookie(request, openidKey);
        String openid = cookie != null ? cookie.getValue() : null;
        logger.trace("PaymentController#wechatpayPrepare() - Get openid [{}] from cookie.", openid);
        
        MoyuOrder order = moyuService.load(MoyuOrder.class, id);
        if(order == null) {
            modelAndView.setViewName("product/moyu-error");
            return modelAndView;
        }
        
        if(!StringUtils.equalsIgnoreCase(openid, order.getOpenid())) {
            modelAndView.setViewName("product/moyu-error");
            return modelAndView;
        }
        
        modelAndView.addObject("order", order);
        
        KdniaoUtils api = new KdniaoUtils();
        try {
          String result = api.getOrderTracesByJson(order.getWuliuCode());
          System.out.print(result);
          Map<String, Object> resultMap = JsonUtils.parse(result);
          String shippers = JsonUtils.toJsonString(resultMap.get("Shippers"));
          List<Map<String, Object>> shippersList = JsonUtils.parseArray(shippers);
          String code = shippersList.get(0).get("ShipperCode").toString();
          modelAndView.addObject("code", code);
          modelAndView.addObject("wuliu", order.getWuliuCode());
          
        } catch (Exception e) {
          modelAndView.setViewName("product/moyu-error");
          return modelAndView;
        }
        
        return modelAndView;
    }
}
